<!--这里是发布信息页面-->
<template>
	<view class="publish-container">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="nav-left" @tap="goBack">
				<image class="back-icon" src="/static/icons/arrow_left.png"></image>
			</view>
			<text class="page-title">发布招标</text>
			<view class="nav-right"></view>
		</view>
		
		<!-- 步骤条 -->
		<view class="steps">
			<view class="step-item" v-for="(step, index) in steps" :key="index" 
				:class="{ 'active': currentStep >= index, 'completed': currentStep > index }">
				<view class="step-circle">
					<text v-if="currentStep <= index">{{ index + 1 }}</text>
					<image v-else class="check-icon" src="/static/icons/search.png"></image>
				</view>
				<text class="step-text">{{ step }}</text>
				<view class="step-line" v-if="index < steps.length - 1"></view>
			</view>
		</view>
		
		<!-- 表单内容 -->
		<swiper class="step-swiper" :current="currentStep" :disable-touch="true">
			
			 <!-- <swiper-item>
			    <scroll-view @touchmove.stop scroll-y class="step-scroll">
			      <view class="step-content">
			        <!-- 这里写实际内容 -->
			        <!-- 直接写在这里会显示！
					
			      </view>
			    </scroll-view>
			  </swiper-item> --> 
			<!-- 步骤一：选择类别 -->
			 <swiper-item>
			   <scroll-view scroll-y class="step-scroll">
			     <view class="step-content">
			       <view class="form-section">
			         <text class="section-title">选择招标类别</text>
			         <view class="category-list">
			           <view class="category-item" v-for="(category, index) in categories" :key="index"
			             :class="{ 'selected': selectedLevel1 === category.id }"
			             @tap="selectLevel1(category.id)">
			             <text class="category-name">{{ category.name }}</text>
			           </view>
			         </view>
			         
			         <text class="section-title" v-if="selectedLevel1 && categor02.length">选择二级类别</text>
			         <view class="category-list" v-if="selectedLevel1 && categor02.length">
			           <view class="category-item" v-for="(category, index) in categor02" :key="index"
			             :class="{ 'selected': selectedLevel2 === category.id }"
			             @tap="selectLevel2(category.id)">
			             <text class="category-name">{{ category.name }}</text>
			           </view>
			         </view>
			         
			         <text class="section-title" v-if="selectedLevel2 && categor03.length">选择三级类别</text>
			         <view class="category-list" v-if="selectedLevel2 && categor03.length">
			           <view class="category-item" v-for="(category, index) in categor03" :key="index"
			             :class="{ 'selected': selectedCategory === category.id }"
			             @tap="selectLevel3(category.id)">
			             <text class="category-name">{{ category.name }}</text>
			           </view>
			         </view>
			       </view>
			     </view>
			   </scroll-view>
			 </swiper-item>
			
			<!-- 步骤二：填写信息 -->
			 <swiper-item>
				<scroll-view scroll-y class="step-scroll">
					<view class="step-content">
						<view class="form-section">
							<text class="section-title">基本信息</text>
							
							<view class="form-item">
								<text class="form-label">招标标题 <text class="required">*</text></text>
								<input class="form-input" v-model="formData.title" placeholder="请输入招标标题" />
							</view>
							
							<view class="form-item">
								<!-- <text class="form-label">项目预算 <text class="required">*</text></text> -->
								<text class="form-label">项目预算</text>
								<view class="budget-input">
									<text class="currency">¥</text>
									<input class="form-input" type="digit" v-model="formData.budget" placeholder="请输入预算金额" />
									<picker class="budget-unit-picker" mode="selector" :range="budgetUnits" @change="onBudgetUnitChange">
										<view class="budget-unit">{{ formData.budgetUnit }}</view>
									</picker>
								</view>
							</view>
							
							<view class="form-item">
								<text class="form-label">截止日期 <text class="required">*</text></text>
								<picker class="form-picker" mode="date" :start="startDate" @change="onDateChange">
									<view class="picker-value">
										<text v-if="formData.deadline">{{ formData.deadline }}</text>
										<text v-else class="placeholder">请选择截止日期</text>
										<image class="picker-arrow" src="/static/icons/calendar.png"></image>
									</view>
								</picker>
							</view>
							
							<view class="form-item">
								<!-- <text class="form-label">所在地区 <text class="required">*</text></text> -->
								<text class="form-label">所在地区 <text>*</text></text>
								<view class="form-picker"  @click="onRegionChange">
									<view class="picker-value">
										<text v-if="formData.region">{{ formData.region }}</text>
										
										<text v-else class="placeholder">请选择所在地区</text>
										<image class="picker-arrow" src="/static/icons/location.png"></image>
									</view>
								</view>
							</view>
						</view>
						
						<view class="form-section">
							<text class="section-title">项目详情</text>
							
							<view class="form-item">
								<text class="form-label">项目描述 <text class="required">*</text></text>
								<textarea class="form-textarea" v-model="formData.description" placeholder="请详细描述项目需求、技术要求等信息..." />
							</view>
							
							<view class="form-item">
								<text class="form-label">联系人 <text class="required">*</text></text>
								<input class="form-input" v-model="formData.contact" placeholder="请输入联系人姓名" />
							</view>
							
							<view class="form-item">
								<text class="form-label">联系电话 <text class="required">*</text></text>
								<input class="form-input" type="number" v-model="formData.phone" placeholder="请输入联系电话" />
							</view>
							
							<view class="form-item">
							<!-- 	<button @tap="totest" >去测试页面</button> -->
							
							      <uni-file-picker
								     
							          v-model="fileValue"
							         file-mediatype="image"  
							           file-extname="jpg,png,pdf,doc,docx"  
							         @select="handleSelect"
							         @progress="handleProgress"
							         @success="handleSuccess"
							         @fail="handleFail"
							       ></uni-file-picker>
								  <button @click="choosePDF" style="width: 200rpx;height: 100rpx; color: hotpink;">PDF文件</button>
							
								<!-- <text class="form-label">附件</text>
								<input class="form-input" type="number" v-model="formData.phone" placeholder="请选择附件" /> -->
							</view>
						</view>
					</view>
				</scroll-view>
			</swiper-item> 
			
			<!-- 步骤三：确认支付 -->
			 <swiper-item>
				<scroll-view scroll-y class="step-scroll">
					<view class="step-content">
						<view class="payment-section">
							<view class="bid-summary">
								<text class="summary-title">招标信息</text>
								<view class="summary-item">
									<text class="item-label">招标类别</text>
									<text class="item-value">{{ getSelectedCategoryName() }}</text>
								</view>
								<view class="summary-item">
									<text class="item-label">招标标题</text>
									<text class="item-value">{{ formData.title }}</text>
								</view>
								<view class="summary-item">
									<text class="item-label">项目预算</text>
									<text class="item-value">¥{{ formData.budget }} {{ formData.budgetUnit }}</text>
								</view>
								<view class="summary-item">
									<text class="item-label">截止日期</text>
									<text class="item-value">{{ formData.deadline }}</text>
								</view>
							</view>
							
							<!-- <view class="payment-options">
								<text class="payment-title">支付方式</text>
								<view class="payment-list">
									<view class="payment-item" 
										v-for="(method, index) in paymentMethods" 
										:key="index"
										:class="{'selected': selectedPayment === method.id}"
										@tap="selectPayment(method.id)">
										<image class="payment-icon" :src="method.icon"></image>
										<text class="payment-name">{{ method.name }}</text>
										<image class="select-icon" v-if="selectedPayment === method.id" src="/static/icons/search.png"></image>
									</view>
								</view>
							</view> -->
							
							<!-- <view class="fee-calculation">
								<text class="fee-title">费用明细</text>
								<view class="fee-item">
									<text class="fee-label">信息发布费</text>
									<text class="fee-value">¥198.00</text>
								</view>
								<view class="fee-item">
									<text class="fee-label">服务费</text>
									<text class="fee-value">¥50.00</text>
								</view>
								<view class="fee-item total">
									<text class="fee-label">合计</text>
									<text class="fee-value">¥248.00</text>
								</view>
							</view> -->
						</view>
					</view>
				</scroll-view>
			</swiper-item> 
		</swiper>
		
		<!-- 底部按钮 -->
		<view class="bottom-bar">
			<button class="prev-btn" v-if="currentStep > 0" @tap="prevStep">上一步</button>
			<button class="next-btn" v-if="currentStep < steps.length - 1" @tap="nextStep">下一步</button>
			<button class="submit-btn" v-if="currentStep === steps.length - 1" @tap="submitBid">确认提交</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed,onMounted } from 'vue';

import { onLoad } from '@dcloudio/uni-app'

// 步骤设置
const steps = ['选择类别', '填写信息', '确认提交'];
const currentStep = ref(0);

const imgs = ref([]) //存放图片的数组

// ✅ 正确声明响应式变量
const imageValue = ref([])  // 用于文件列表绑定（如果使用 uni-file-picker）
const fileValue= ref([]) // 确保这里定义了 fileValue
// 定义响应式文件列表
const uploadTask = ref(null) // 上传任务对象
const plat = ref("")
const  info = ref({})
  // 通用文件选择（PDF等）
  
 //------------------------------------------->
   // 1. 组件引用
   const uploadRef = ref(null);
   
   // 2. 配置项（响应式数据）
const totest = ()=>{
	uni.navigateTo({
		url:'/pages/bid/test'
	})
}


  //------------------------------------------->
 
  const choosePDF = ()=> {
   plus.io.chooseFile({ 
     title: '选择文件',
     filetypes: ['docx', 'zip', 'pdf'],
     multiple: false
   }, (e) => {
     const filePath = e.files[0]; // 单选模式取第一个文件
     console.log('文件路径:', filePath);
 
     // 识别 content:// 路径
     if (filePath.startsWith('content://')) {
       uni.showToast({
         title: '当前路径不支持，请选择其他上传方式',
         icon: 'none',
         duration: 3000
       });
       console.error('不支持的路径类型:', filePath);
     } 
     // 处理标准存储路径
     else if (filePath.startsWith('/storage/emulated/0/')) {
       uploadFile(filePath); // 调用上传方法
     }
     // 其他合法路径（如 file:// 开头）
     else {
       console.log('直接上传路径:', filePath);
        uploadFile(filePath);
     }
   });
 }
 	
// 文件上传
const uploadFile = (filePath) => {
  uni.uploadFile({
    url: 'http://115.190.38.218/go/api/v1/upload',
    filePath: filePath,
    name: 'file',
    success: (res) => {
      console.log('上传成功', res.data)
      uni.showToast({ title: '上传成功' })
    },
    fail: (err) => {
      console.error('上传失败', err)
      uni.showToast({ title: '上传失败', icon: 'none' })
    }
  })
}
  
  
  
  
// 处理文件选择
const handleSelect = async (e) => {
  try {
    // 获取文件对象
    const file = e.tempFiles[0]
    if (!file) {
      uni.showToast({ title: '未选择文件', icon: 'none' })
      return
    }

    // 处理安卓 content:// 路径
    // #ifdef APP-PLUS
    const realPath = file.path.startsWith('content://') ? 
      await convertContentUri(file.path) : 
      file.path
    // #endif
    // #ifndef APP-PLUS
    const realPath = file.path
    // #endif
    
	
	
    // 执行上传
    uploadTask.value = uni.uploadFile({
      url: "http://115.190.38.218/go/api/v1/upload", // 补全API路径
      filePath: realPath,
      name: 'file',
      formData: {
        // userId: info.value.id_card,
        category: 'documents'
      },
      header: {
        'Authorization': 'Bearer your_token',
        'X-Custom-Header': 'value'
      },
      success: (res) => {
        console.log('原始响应:', res)
        try {
          const data = JSON.parse(res.data)
          console.log('上传成功:', data)
		  imgs.value.push(data.data.url)
		  
          uni.showToast({ title: '上传成功' })
        } catch (e) {
          console.error('JSON解析失败:', e)
        }
      }
    })
  } catch (err) {
    console.error('选择文件错误:', err)
  }
}

// Android路径转换方法
// #ifdef APP-PLUS
const convertContentUri = (uri) => {
  return new Promise((resolve) => {
    plus.io.resolveLocalFileSystemURL(
      uri,
      (entry) => resolve(entry.toLocalURL()),
      (e) => {
        console.error('路径转换失败:', e.message)
        resolve(uri) // 降级处理
      }
    )
  })
}
// #endif

// 其他处理函数
const handleProgress = (e) => {
  console.log(`上传进度：${e.progress}%`)
  // 可以在此显示进度条
}

const handleSuccess = (e) => {
  // 组件自带的上传成功回调（如果你配置了autoUpload）
}

const handleFail = (err) => {
  console.error('失败原因:', err.errMsg)
  uni.showToast({ title: `上传失败：${err.errMsg}`, icon: 'none' })
}

// 取消上传（可选）
const cancelUpload = () => {
  if (uploadTask.value) {
    uploadTask.value.abort()
    uni.showToast({ title: '已取消上传', icon: 'none' })
  }
}

// 类别数据
// const categories = ref([
// 	{ id: 1, name: '工业标单', icon: '/static/icons/category/Industrial.png' },

// ]);
// // 类别二数据
// const categor02 = ref([
// ]);
// // 类别三数据
// const categor03 = ref([
// ]);

// 响应式数据
const categories = ref([]) // 一级分类（name去重）
const categor02 = ref([])  // 二级分类（code02去重）
const categor03 = ref([])  // 三级分类（code03）
const allCategories = ref([]) // 存储所有分类数据
const selectedCategory = ref(null)
const selectedLevel1 = ref(null)
const selectedLevel2 = ref(null)



// 选择一级分类
const selectLevel1 = (id) => {
  selectedLevel1.value = id
  selectedLevel2.value = null
  selectedCategory.value = null
  
  const level1Name = allCategories.value.find(item => item.codeid === id)?.name;
  
  // 步骤1：先用Set对code02去重
  const uniqueCode02 = [...new Set(
    allCategories.value
      .filter(item => item.name === level1Name && item.code02 !== null)
      .map(item => item.code02) // 仅提取code02字段
  )];
  
  // 步骤2：根据去重后的code02匹配第一个完整对象
  categor02.value = uniqueCode02.map(code02 => {
    const firstMatch = allCategories.value.find(item => item.code02 === code02);
    return { id: firstMatch.codeid, name: firstMatch.code02 };
  });
  
  console.log("二级去重结果：", categor02.value);
  
  // 清空三级分类
  categor03.value = []
}

// 选择二级分类
const selectLevel2 = (id) => {
  selectedLevel2.value = id
  selectedCategory.value = null
  
  // 更新三级分类（基于code03）
  const level2Name = allCategories.value.find(item => item.codeid === id)?.code02
  categor03.value = allCategories.value
    .filter(item => item.code02 === level2Name && item.code03 !== null)
    .map(item => ({ id: item.codeid, name: item.code03 }))
	
	console.log("二级选择结果，到这里就结束了：",level2Name)
	
	console.log("类别三的结果：",categor03.value)
	if(categor03.value.length == 0){
	 selectedCategory.value = id
	}
}

// 选择三级分类
const selectLevel3 = (id) => {
  selectedCategory.value = id
  console.log('最终选择的分类ID:', id)
}

// 表单数据
const budgetUnits = ['元', '千元', '万元', '百万'];
const startDate = new Date().toISOString().split('T')[0]; // 今天的日期

const formData = ref({
	title: '',
	budget: '',
	budgetUnit: '万元',
	deadline: '',
	region: '',
	description: '',
	contact: '',
	phone: ''
});

// 支付方式
const paymentMethods = ref([
	{ id: 1, name: '微信支付', icon: '/static/icons/category/more.png' },
	{ id: 2, name: '支付宝', icon: '/static/icons/category/more.png' },
	{ id: 3, name: '银行卡', icon: '/static/icons/category/more.png' }
]);
const selectedPayment = ref(1);

// 方法
const selectCategory = (id) => {
	selectedCategory.value = id;
};


onLoad((optins)=>{
	console.log("1111------------>>>")
	
	const ishave =  uni.getStorageSync("token")
	info.value =  uni.getStorageSync("info")
	
	console.log("发布：",ishave)
	uni.request({
		url:'http://115.190.38.218/go/api/v1/check/ck',
		method:'GET',
		header: { 'Content-Type': 'application/json' ,
		  'Authorization': `Bearer ${ishave}` // 关键！格式必须为 "Bearer {token}"
		},
		success: (res) => {
			console.log("验证结果：",res)
			if(res.data.error == "无效令牌"){
				uni.showToast({
					title:"过期，重新登录",
					icon:'error'
				})
				
				uni.navigateTo({
					url:'/pages/login/login'
				})
			}
		},
		fail: (err) => {
			console.log("验证失败：",err)
		}
	})
	
	console.log("用户信息：",info.value)
	if(ishave){
		console.log("ll")
		uni.request({
			url:'http://115.190.38.218/go/api/v1/categories',
			method:'GET',
			success:function(res){
				console.log("获取结果：",res)
				
				   allCategories.value = res.data.data
				    
				    // 初始化一级分类（基于name字段去重）
				       categories.value = [...new Set(
				         allCategories.value
				           .filter(item => item.code02 === null) // 一级分类的code02为null
				           .map(item => ({ id: item.codeid, name: item.name }))
				       )]
					  
					  console.log("去重结果：",categories.value)
			},
			fail:function(err){
				console.log("出现错误：",err)
			}
		})
		
	}else{
		uni.navigateTo({
			url:'/pages/login/login'
		})
	}
})
const onBudgetUnitChange = (e) => {
	const index = e.detail.value;
	formData.value.budgetUnit = budgetUnits[index];
};

const onDateChange = (e) => {
	formData.value.deadline = e.detail.value;
};

const onRegionChange = (e) => {//获取经纬度信息 
    // 1. 调用 UniApp 获取经纬度  
    uni.getLocation({  
      type: 'gcj02',  // 必须用高德坐标系  
      geocode: true,   // App 端直接返回地址（H5 无效）  
      success: (res) => {  
		  console.log("返回的信息包括哪些？",res)
        console.log('经纬度:', res.latitude, res.longitude); 
		 formData.value.region = `${res.address.province}${res.address.city}${res.address.district}${res.address.street}${res.address.poiName}${res.address.streetNum}`;
        // App 端直接返回地址（res.address） 
		
        // H5/小程序需额外调用高德逆地理编码  
        if (!res.address) this.reverseGeocode(res.longitude, res.latitude);  
      }  
    }); 
	formData.value.region = e.detail.value.join(' ');
};

const getSelectedCategoryName = () => {
	const category = categories.value.find(item => item.id === selectedCategory.value);
	return category ? category.name : '未选择';
};

const selectPayment = (id) => {
	selectedPayment.value = id;
};

const validateStep = () => {
	if (currentStep.value === 0) {
		if (!selectedCategory.value) {
			uni.showToast({
				title: '请选择招标类别',
				icon: 'none'
			});
			return false;
		}
	} else if (currentStep.value === 1) {
		if (!formData.value.title) {
			uni.showToast({
				title: '请输入招标标题',
				icon: 'none'
			});
			return false;
		}
		// if (!formData.value.budget) {
		// 	uni.showToast({
		// 		title: '请输入项目预算',
		// 		icon: 'none'
		// 	});
		// 	return false;
		// }
		if (!formData.value.deadline) {
			uni.showToast({
				title: '请选择截止日期',
				icon: 'none'
			});
			return false;
		}
		// if (!formData.value.region) {
		// 	uni.showToast({
		// 		title: '请选择所在地区',
		// 		icon: 'none'
		// 	});
		// 	return false;
		// }
		if (!formData.value.description) {
			uni.showToast({
				title: '请输入项目描述',
				icon: 'none'
			});
			return false;
		}
		if (!formData.value.contact) {
			uni.showToast({
				title: '请输入联系人姓名',
				icon: 'none'
			});
			return false;
		}
		if (!formData.value.phone) {
			uni.showToast({
				title: '请输入联系电话',
				icon: 'none'
			});
			return false;
		}
	}
	
	return true;
};

const nextStep = () => {
	if(categor03.value.length == 0){
		if (currentStep.value < steps.length - 1) {
			currentStep.value++;
		}
	}else{
		if (!validateStep()) return;
		
		if (currentStep.value < steps.length - 1) {
			currentStep.value++;
		}
	}
	
};

const prevStep = () => {
	if (currentStep.value > 0) {
		currentStep.value--;
	}
};
// 转换deadline为合法ISO 8601格式
const formatDeadline = (deadline) => {
    if (!deadline || deadline === '0000-00-00') {
        return new Date().toISOString(); // 默认当前时间
    }
    try {
        return new Date(deadline).toISOString();
    } catch (e) {
        console.error("日期格式错误，使用默认值:", e);
        return new Date().toISOString();
    }
};

 // 获取支付参数（从后端API）
    const getPaymentParams = async (orderInfo) => {
      const token = uni.getStorageSync('token');
      try {
        const response = await uni.request({
          url: 'http://115.190.38.218/go/api/v1/wechat/payment',
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          data: {
            order_id: orderInfo.orderId,
            amount: orderInfo.amount,
            description: '招标保证金支付'
          }
        });
        
        if (response.data.code === 200 && response.data.data) {
          return response.data.data;
        } else {
          throw new Error(response.data.message || '获取支付参数失败');
        }
      } catch (error) {
        console.error('获取支付参数出错:', error);
        throw error;
      }
    };
	
const submitProjectAfterPayment = ()=> {
	   const token = uni.getStorageSync('token');
	   let is_qi = uni.getStorageSync("info")
	   let flag = ""
	   if('company_name' in is_qi){
		   flag = "是"
	   }else{
		    flag = "否"
	   }
	   if (!token) {
	       uni.showToast({ title: '请先登录', icon: 'none' });
	       return;
	   }
		uni.request({
		    url: 'http://115.190.38.218/go/api/v1/projects',
		    method: 'POST',
		    header: { 'Content-Type': 'application/json' ,
			  'Authorization': `Bearer ${token}` // 关键！格式必须为 "Bearer {token}"
			}, // 必须设置
		    data: {
		        // 必填字段（根据后端binding规则）
				     // 包含支付订单号用于关联
				    //payment_order_no: orderNo,  //订单号后期加上
				    title: formData.value.title,           // 招标标题
		            user_id: info.value.id_card,                  // 项目发布人ID（需从登录态获取）
		            code_id: selectedCategory.value,         // 招标类别ID
		           
		            description: formData.value.description, // 详细描述
		            budget_min: parseFloat(formData.value.budget) || 0.0, // 转为浮点数,                 // 最低预算（浮点数）
		            budget_max: 150000.00,                 // 最高预算（浮点数）
		            deadline: formatDeadline(formData.value.deadline), // 关键修改,      // 截止时间（ISO 8601格式）
		            location: formData.value.region,              // 所在地区
		            project_type: '装修工程',               // 项目类型
		            contact_info: formData.value.phone,     // 联系方式
		            company_name: info.value.company_name,
					is_qi: flag,  //是否是企业用户发布的信息
		            // 可选字段（根据omitempty标签，可省略）
		            status: 'published',                     // 状态（如未传，后端可能设默认值）
		            is_verified: false,                    // 是否已验证
		            files: [                               // 文件附件（数组）
		              { 
		                file_name: '招标书.pdf', 
		                file_url: 'https://example.com/files/1.pdf' 
		              }
		            ],
		            images: imgs.value
		    },  
		    success: (res) => { /* 处理响应 */ 
			console.log("发布！",res)
			 if(res.data.data){
				   uni.showModal({
				   	title: '支付成功',
				   	content: '您的招标信息已发布成功！',
				   	showCancel: false,
				   	success: () => {
				   		// 跳转到投标成功页面
				   		uni.redirectTo({
				   			url: '/pages/bid/bid-publish-success'
				   		});
				   	}
				   });
			 }else{
				 console.log("失败！")
			 }
			 },
		    fail: (err) => { /* 处理错误 */ 
			console.log("发布失败！",err)
			}
		});
	}
	const requestOrderFromBackend =  (token) => {
		
		console.log("调用了没有？","标题能获取吗？：",formData.value.title)
	    uni.request({
	    url:"http://115.190.38.218/go/api/v1/projects/pay/allpay",//http://115.190.38.218/go/ms/alipay
	    method: 'POST',
		header: { 'Content-Type': 'application/json' ,
		  'Authorization': `Bearer ${token}` // 关键！格式必须为 "Bearer {token}"
		}, // 必须设置
	    data: { amount: 100, product: formData.value.title } ,// 自定义参数
		success:(res)=>{
			console.log("后端返回的参数：",res)
			if(res.data.code==200){
				 const payData = res.data.data;
					  uni.requestPayment({
					    provider: 'alipay',
					    orderInfo: payData.order_info, // 使用后端返回的支付字符串
					    success: (res) => {
					      console.log("支付成功", res);
						  
						  
					      //resolve();   支付成功了才有下面的
						  submitProjectAfterPayment(payData.out_trade_no)
						  
					    },
					    fail: (err) => {
					      console.log("支付失败", err);
					      reject(err);
					    }
					  });
			}else{
				console.log("出错：",res)
			}
		},
		fail:function(err){
			console.log("后端返回失败的情况：",err)
		}
	  });
	 console.log("到底执行了没有！！！")
	
	};
	
const submitBid =  async() => {
	// uni.showLoading({
	// 	title: '支付中...'
	// });
	// 从本地缓存获取 token（示例为 uni-app）
	const token = uni.getStorageSync('token'); 
	if (!token) {
	    uni.showToast({ title: '请先登录', icon: 'none' });
	    return;
	}
	console.log("日期：",formData.value.deadline)
	console.log("图片数组中的值：",imgs.value)
	//支付开始---------------------
	//this.threquestOrderFromBackend()//调用
	
    // requestOrderFromBackend(token) //这里现在移走了
	submitProjectAfterPayment() //暂时先改为这样
	
	//支付结束---------------------
	//替换真实请求
	
	// 模拟支付过程
	// setTimeout(() => {
	// 	uni.hideLoading();
		 // 3. 获取微信支付参数
		//         const paymentParams = await getPaymentParams({
		//           orderId: `BID_${projectId}_${Date.now()}`,
		//           amount: 6999, // 保证金金额（分）
		//           description: `招标项目: ${formData.value.title}保证金`
		//         });
		
		//         console.log('支付参数:', paymentParams);
		
		//         // 4. 发起微信支付
		//         uni.hideLoading();
		//         const paymentResult = await new Promise((resolve, reject) => {
		//           uni.requestPayment({
		//             provider: 'wxpay',
		//             orderInfo: paymentParams,
		//             success: resolve,
		//             fail: reject
		//           });
		//         });
		
		//         console.log('支付结果:', paymentResult);

	
	// }, 2000);
	
};

const goBack = () => {
	//uni.navigateBack();
	uni.switchTab({
		url: '/pages/index/index'
	});

};

const  handleUpload =(e) => {
	 console.log("事件对象:", e);
	       
	       // App端文件路径获取方式
	       // 注意：App端数据字段为 tempFiles 而非 tempFilePaths
	       if (e.tempFiles && e.tempFiles.length > 0) {
	         const file = e.tempFiles[0];
	         console.log("文件对象:", {
	           path: file.path,
	           name: file.name,
	           size: file.size,
	           type: file.type
	         });
	 
	         // 执行上传
	         uni.uploadFile({
	           url: 'https://your-api.com/upload',
	           filePath: file.path,  // 正确路径获取方式
	           name: 'file',
	           header: {
	             'Authorization': 'Bearer your_token'
	           },
	           success: (res) => {
	             const data = JSON.parse(res.data);
	             uni.showToast({ title: '上传成功', icon: 'success' });
	             console.log('服务器响应:', data);
	           },
	           fail: (err) => {
	             uni.showToast({ title: '上传失败', icon: 'none' });
	             console.error('上传错误:', err);
	           }
	         });
	       } else {
	         uni.showToast({ title: '未选择文件', icon: 'none' });
	       }
    }
  

const chooseQualificationFile = () =>{
	console.log("点击了上传附件,")
	// 选择文件（支持多平台）
	// 判断平台
	// 正确插件名为 UniFilePicker（无DCloud-前缀）
	// 选择文件
	plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
	  const filePicker = plus.io.createPicker({
	    filter: "*/*",
	    multiple: false
	  });
	  filePicker.pick(function(file) {
	    console.log("选择的文件:", file.fullPath);
	  }, function(e) {
	    console.error("取消选择:", e.message);
	  });
	});
}
</script> 

<style>
.publish-container {
	/* min-height: 100vh; */
	height: 100%;
	background-color: #f5f7fa;
	display: flex;
	flex-direction: column;
}


.navbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	height: 100rpx;
	background-color: #fff;
	border-bottom: 1px solid #f0f0f0;
}

.nav-left, .nav-right {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	width: 40rpx;
	height: 40rpx;
}

.page-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
}

.steps {
	display: flex;
	justify-content: space-between;
	padding: 40rpx 60rpx;
	background-color: #fff;
}

.step-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
}

.step-circle {
	width: 50rpx;
	height: 50rpx;
	border-radius: 25rpx;
	background-color: #ddd;
	color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	margin-bottom: 16rpx;
	z-index: 2;
}

.step-item.active .step-circle {
	background-color: #1d4ed8;
}

.step-item.completed .step-circle {
	background-color: #10b981;
}

.check-icon {
	width: 24rpx;
	height: 24rpx;
}

.step-text {
	font-size: 24rpx;
	color: #666;
}

.step-item.active .step-text,
.step-item.completed .step-text {
	color: #1d4ed8;
	font-weight: 500;
}

.step-line {
	position: absolute;
	top: 25rpx;
	left: 50%;
	height: 2rpx;
	width: 100%;
	background-color: #ddd;
	z-index: 1;
}

.step-item.active .step-line,
.step-item.completed .step-line {
	background-color: #1d4ed8;
}

.step-swiper {
	flex: 1;
	 height: calc(100vh - 180rpx); /* 添加明确高度 */
	width: 100%;
	
}

.step-scroll {
	height: 100%; /* 改为100%而不是固定计算 */
}

.step-content {
	padding: 30rpx;
	min-height: 100%; /* 确保内容区域至少填满可用空间 */
	background-color: #f5f7fa; /* 添加背景色以便调试 */
}


.form-section {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 30rpx;
	position: relative;
	padding-left: 20rpx;
}

.section-title::before {
	content: '';
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	width: 8rpx;
	height: 32rpx;
	background-color: #1d4ed8;
	border-radius: 4rpx;
}

.category-list {
	display: flex;
	flex-wrap: wrap;
	margin: 0 -10rpx;
}

.category-item {
	width: calc(33.33% - 10rpx);
	height: 80rpx;
	margin: 10rpx;
	background-color: #f9fafb;
	border-radius: 16rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	border: 2rpx solid transparent;
}

.category-item.selected {
	background-color: rgba(29, 78, 216, 0.05);
	border-color: #1d4ed8;
}

.category-icon {
	width: 64rpx;
	height: 64rpx;
	margin-bottom: 16rpx;
}

.category-name {
	font-size: 26rpx;
	color: #333;
}

.form-item {
	margin-bottom: 30rpx;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.required {
	color: #ef4444;
	margin-left: 4rpx;
}

.form-input {
	width: 100%;
	height: 90rpx;
	background-color: #f9fafb;
	border: 1px solid #e5e7eb;
	border-radius: 12rpx;
	padding: 0 24rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
}

.budget-input {
	display: flex;
	align-items: center;
	width: 100%;
	height: 90rpx;
	background-color: #f9fafb;
	border: 1px solid #e5e7eb;
	border-radius: 12rpx;
	padding: 0 24rpx;
}

.currency {
	font-size: 28rpx;
	color: #333;
	margin-right: 16rpx;
}

.budget-input .form-input {
	flex: 1;
	border: none;
	background: transparent;
	padding: 0;
}

.budget-unit-picker {
	width: 160rpx;
	height: 90rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-left: 1px solid #e5e7eb;
	margin-right: -24rpx;
}

.budget-unit {
	font-size: 28rpx;
	color: #333;
}

.form-textarea {
	width: 100%;
	height: 240rpx;
	background-color: #f9fafb;
	border: 1px solid #e5e7eb;
	border-radius: 12rpx;
	padding: 24rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
}

.form-picker {
	width: 100%;
	height: 90rpx;
	background-color: #f9fafb;
	border: 1px solid #e5e7eb;
	border-radius: 12rpx;
	box-sizing: border-box;
}

.picker-value {
	height: 90rpx;
	display: flex;
	align-items: center;
	padding: 0 24rpx;
	justify-content: space-between;
}

.placeholder {
	color: #9ca3af;
}

.picker-arrow {
	width: 32rpx;
	height: 32rpx;
}

.payment-section {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.bid-summary, .payment-options, .fee-calculation {
	border-bottom: 1px solid #f0f0f0;
	padding-bottom: 30rpx;
	margin-bottom: 30rpx;
}

.fee-calculation {
	border-bottom: none;
	margin-bottom: 0;
	padding-bottom: 0;
}

.summary-title, .payment-title, .fee-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
}

.summary-item, .fee-item {
	display: flex;
	justify-content: space-between;
	margin-bottom: 16rpx;
}

.item-label, .fee-label {
	font-size: 28rpx;
	color: #666;
}

.item-value, .fee-value {
	font-size: 28rpx;
	color: #333;
}

.fee-item.total {
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1px solid #f0f0f0;
}

.fee-item.total .fee-label,
.fee-item.total .fee-value {
	font-size: 32rpx;
	font-weight: 600;
	color: #1d4ed8;
}

.payment-list {
	display: flex;
	flex-direction: column;
}

.payment-item {
	display: flex;
	align-items: center;
	padding: 24rpx 0;
	border-bottom: 1px solid #f0f0f0;
}

.payment-item:last-child {
	border-bottom: none;
}

.payment-icon {
	width: 48rpx;
	height: 48rpx;
	margin-right: 20rpx;
}

.payment-name {
	flex: 1;
	font-size: 28rpx;
	color: #333;
}

.select-icon {
	width: 40rpx;
	height: 40rpx;
}

.bottom-bar {
	height: 140rpx;
	background-color: #fff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
}

.prev-btn, .next-btn, .submit-btn {
	height: 88rpx;
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 30rpx;
	font-weight: 600;
}

.prev-btn {
	width: 200rpx;
	background-color: #f3f4f6;
	color: #6b7280;
}

.next-btn, .submit-btn {
	flex: 1;
	background-color: #1d4ed8;
	color: #fff;
	margin-left: 20rpx;
}

.bottom-bar .prev-btn + .next-btn,
.bottom-bar .prev-btn + .submit-btn {
	flex: 1;
}
  




/* 4. 样式优化 */
.upload-btn {
  padding: 12px 24px;
  background: #409eff;
  color: white;
  border-radius: 4px;
  border: none;
  font-size: 14px;
}

.upload-btn:active {
  background: #3a8ee6;
}
</style>